#!/bin/env python3
# -*- coding:utf-8 -*-
"""
    [模块名]
    Add By :e4ting e4ting@gmail.com 2023-09-24 16:33:29
"""
import sys,os
import json,time
from pdb import set_trace as strace
from traceback  import format_exc as dumpstack
from textwrap import dedent

from flask_restful import Resource
from flask         import redirect,request,make_response

from core.webhook  import Robot,MessageTemp
from e4ting        import util,log

class WebRobots(Resource):
    ''' 机器人管理 '''
    #----------------------------------------------------------------------
    def __init__(self):
        super(WebRobots, self).__init__()

    def get(self, **kwargs):
        robots = Robot.load_all()
        data = [ _.webdumps() for _ in robots]
        data.sort(key=lambda x:x.get("uptime"), reverse=True)
        # payload = dict(data=data, )
        return dict(code=200, data=data, total=len(data))

    def post(self, id=0, **kwargs):
        """
            修改 机器人
        """
        data = request.json
        _id = data.get("id")
        log.info(f"修改机器人 {_id} {data}")
        # if not _id:
        #     return dict(code=400, data="修改失败")
        # _id = int(_id)
        Robot.update(_id, name=data["name"], token=data["token"], type=data["type"])
        return dict(code=200, data="修改成功 : {name}".format(**data))

    def put(self, id=0, **kwargs):
        """
            创建 机器
        """
        data = request.json
        log.info(data)
        Robot.update(name=data["name"], token=data["token"], type=data["type"])
        # Robot.update(_id="test_wx",       name="测试企微机器人", token="https://wx.cn/access_toker=xxx", type=WeiXinRobot.name)
        return dict(code=200, data="创建成功 : {name}".format(**data))

    def delete(self, id=0, **kwargs):
        """
            删除 机器人
        """
        _id = id or request.args.get("id") or request.json.get("id")
        log.info(f"删除机器人 {_id}")
        if not _id:
            return dict(code=400, data="删除失败")
        ret = Robot.delete(_id)
        if not ret:
             return dict(code=400, data="删除失败")
        return dict(code=200, data="删除成功 : {name} ( {_id} )".format(**ret))

